package com.momo.hr.service;

import com.momo.hr.bean.Hr;
import com.momo.hr.mapper.HrMapper;
import com.momo.hr.mapper.HrRoleMapper;
import com.momo.hr.util.HrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class HrService implements UserDetailsService {
    @Autowired
    HrMapper hrMapper;

    @Autowired
    HrRoleMapper hrRoleMapper;


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //通过名字查询用户
        Hr hr = hrMapper.loadUserByUsername(s);
        if( hr == null ){
            throw new UsernameNotFoundException("用户名不存");//抛出用户名不存在的异常
        }
        //如果登录成功,那么就根据登录成功后的Id查询出当前用户所对应的所有角色信息
        hr.setRoles(hrMapper.getRolesById(hr.getId()));
        return hr;
    }

    public List<Hr> getAllHrs(String keywords) {
        Integer id = HrUtils.getCurrentHr().getId();
        return this.hrMapper.getAllHrs(id,keywords);
    }

    public int updateHr(Hr hr) {
        return this.hrMapper.updateByPrimaryKeySelective(hr);
    }

    @Transactional
    public boolean updateHrRoles(Integer hrid, Integer[] ids) {
        this.hrRoleMapper.deleteByHrid(hrid);
        return hrRoleMapper.addRole(hrid,ids) == ids.length;
    }

    public List<Hr> getAllHrsExceptCurrentHr() {
        return this.hrMapper.getAllHrsExceptCurrentHr(HrUtils.getCurrentHr().getId());
    }

    public boolean updatePassword(String oldpass, String pass, Integer hrid) {
        //先去旧密码是否正确
        Hr hr = this.hrMapper.selectByPrimaryKey(hrid);
        //使用BCryptPasswordEncoder来使得明文密码和加密后密码进行匹配比较
        BCryptPasswordEncoder bpe = new BCryptPasswordEncoder();
        if(hr != null  && bpe.matches(oldpass,hr.getPassword())){
            String encode = bpe.encode(pass);//密码加密
            Integer result = hrMapper.updatePasswordByHrId(hrid,encode);//更新密码
            return result == 1;
        } else {
            return false;
        }
    }

    public Boolean updateUserFace(String url, Integer id) {
        return this.hrMapper.updateUserFaceByPrimaryId(url,id) == 1;
    }
}
